/**
 * 
 */
package jp.ekasi.pms.ui.util;

import java.io.File;

import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.util.URI;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;

/**
 * @author sumari
 *
 */
public class WorkbenchUtil {
	
	public static String openFilePathDialog(Shell shell, String fileExtensionFilter, int style) {
		FileDialog fileDialog = new FileDialog(shell, style);
		if (fileExtensionFilter != null) {
			fileDialog.setFilterExtensions(new String[]{fileExtensionFilter});
		}
	
		fileDialog.open();
		if (fileDialog.getFileName() != null && fileDialog.getFileName().length() > 0) {
			return fileDialog.getFilterPath() + File.separator + fileDialog.getFileName();
		}
		else {
			return null;
		}
	}
	
	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public static boolean openEditor(IWorkbench workbench, URI fileURI) {
		IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
		IWorkbenchPage page = workbenchWindow.getActivePage();
	
		IEditorDescriptor editorDescriptor = workbench.getEditorRegistry().getDefaultEditor(fileURI.toFileString());
		if (editorDescriptor == null) {
			MessageDialog.openError(
			workbenchWindow.getShell(),
			"", 
			""); 
			return false;
		}
		else {
			try {
				page.openEditor(new URIEditorInput(fileURI), editorDescriptor.getId());
			}
			catch (PartInitException exception) {
				MessageDialog.openError(
				workbenchWindow.getShell(),
				"", 
				exception.getMessage());
				return false;
			}
		}
	
		return true;
	}

}
